//导入组件
import { createRouter, createWebHashHistory } from 'vue-router'
import BookListHome from "../views/BookListHome.vue"
import Login from "../views/Login.vue"
import Home1 from "../views/Home1.vue"
import BookList from "../views/booklist.vue"
import Information from "../views/Information.vue"
import Spendlist from "../views/Spendlist.vue"
import Comments from "../views/Comments.vue"
import Borrow from "../views/Borrow.vue"
import Register from "../views/Register.vue"
import Admin_home from "../views/Admin_Home.vue"
import Admin_booklist from "../views/Admin_booklist.vue"
import Admin_userlist from "../views/Admin_userlist.vue"

import { useUserStore } from "../stores/user.js";

// 定义路由信息
const routes = [
    {
        path: "/",
        component: Login
    },
    {
        path: "/register",
        component: Register
    },
    {
        path: "/home1",
        component: Home1,
        // 重定向
        redirect: '/home1/booklist',
        // 子路由
        children: [
            {
                path: 'booklist',
                component: BookList
            },
            {
                path: 'information',
                component: Information
            },
            {
                path: 'spendlist',
                component: Spendlist
            },
            {
                path: 'comments',
                component: Comments
            },
            {
                path: "borrowbook",
                component: Borrow
            },
        ]
    },
    {
        path: "/adminHome",
        component: Admin_home,
        // 重定向
        redirect: '/adminHome/admin_booklist',
        // 子路由
        children: [
            {
                path: "admin_booklist",
                component: Admin_booklist
            },
            {
                path: "admin_userlist",
                component: Admin_userlist
            },

        ]
    }

]

// 创建路由实例
const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 路由守卫，
router.beforeEach((to, from, next) => {
    if (to.path === "/" || to.path === "/register" || to.path === "/logout") {
        // 要是去的页面是登陆页面，证明退出登录了，所以清除本地存储
        localStorage.removeItem("user")
        // location.reload()
        next()
    }
    const store = useUserStore()  // 拿到用户对象信息
    // 获取缓存中的用户token
    const token = store.managerInfo.token
    // 如果token不存在，就说明还没有登录或者token过期
    if (!token) {
        next("/")
    }
    next();

})

// 给不同的文件使用要导出，给main.js使用
export default router